<?php

namespace app\http\middleware;

use app\common\Status;

class Sign
{
    // 不校验签名接口
    protected $not_check = [];
    protected $secret = "jvyaK9SRmGZRLFiY";

    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     */
    public function handle($request, \Closure $next)
    {
        $param = $request->param();
        $route = $request->url();

        $module = $request->module();
        // 获取图形验证码
        if (strstr($route, 'getImgCode')) {
            return $next($request);
        }
        if (!in_array($route, $this->not_check) && $module != 'admin') {
            if (!isset($param['timestamp']) || empty($param['timestamp'])) {
                return returnJson(Status::PARAM_ERR, lang('sign_param_err'));
            }
            if (!isset($param['sign']) || empty($param['sign'])) {
                return returnJson(Status::PARAM_ERR, lang('sign_param_err'));
            }
            // 验证请求,5分钟有效
            if (time() - $param['timestamp'] > 60) {
                return returnJson(Status::SIGN_OVERDUE, lang('Signature expired'));
            }
            // 兼容TP不同版本
            if (isset($param['s'])) {
                unset($param['s']);
            }
            $sign = $param['sign'];
            unset($param['sign']);
            ksort($param);
            $params = urlencode(urldecode(http_build_query($param)));
            // $secret是通过key在api的数据库中查询得到
            $sign2 = md5($params . $this->secret);
            if ($sign != $sign2) {
                return returnJson(Status::SIGN_FAIL, lang('Signature error'));
            }
        }
        return $next($request);
    }
}
